/*******************************************************************************
 * Copyright (c) 2010-2011 Robert Fraser                                       *
 *                                                                             *
 * Permission is hereby granted, free of charge, to any person obtaining a     *
 * copy of this software and associated documentation files (the "Software"),  *
 * to deal in the Software without restriction, including without limitation   *
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,    *
 * and/or sell copies of the Software, and to permit persons to whom the       *
 * Software is furnished to do so, subject to the following conditions:        *
 *                                                                             *
 *   - The above copyright notice and this permission notice shall be included *
 *     in all copies or substantial portions of the Software.                  *
 *                                                                             *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,    *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER      *
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING     *
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER         *
 * DEALINGS IN THE SOFTWARE.                                                   *
 *******************************************************************************/

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using GraphSharp.Algorithms.Layout;
using GraphSharp.Algorithms.Layout.Simple.Hierarchical;
using QuickGraph;
using zeal.util;

namespace zeal.ui.graph
{
    internal static class LayoutManager
    {
        private static readonly Log _log = LogManager.getLog(typeof(LayoutManager));
        
        private const string ALGORITHM_NAME = "EfficientSugiyama";
        private const double MIN_CANVAS_OFFSET = GraphEditor.GRID_SIZE * 2;
        private static readonly StandardLayoutAlgorithmFactory<GraphNode, LayoutEdge, BidirectionalGraph<GraphNode, LayoutEdge>> _factory =
            new StandardLayoutAlgorithmFactory<GraphNode, LayoutEdge, BidirectionalGraph<GraphNode, LayoutEdge>>();
        private static readonly EfficientSugiyamaLayoutParameters _parameters = new EfficientSugiyamaLayoutParameters
        {
            VertexDistance = GraphEditor.GRID_SIZE * 2,
            MinimizeEdgeLength = false,
            LayerDistance = GraphEditor.GRID_SIZE * 4
        };

        public static bool layout(GraphEditor editor)
        {
            // TODO use a background thread
            editor.isEnabled = false;
            editor.cursor = Cursors.Wait;
            try
            {
                BidirectionalGraph<GraphNode, LayoutEdge> graph = new BidirectionalGraph<GraphNode, LayoutEdge>();
                Dictionary<GraphNode, Point> positions = new Dictionary<GraphNode, Point>();
                Dictionary<GraphNode, Size> sizes = new Dictionary<GraphNode, Size>();

                int nodeCount = 0;
                foreach (GraphNode node in editor.nodes)
                {
                    Size size = node.RenderSize;
                    nodeCount++;
                    graph.AddVertex(node);
                    Point p = new Point(node.left + size.Width / 2, node.top + size.Height / 2);
                    positions.Add(node, reverse(p));
                    sizes.Add(node, reverse(size));
                }

                int edgeCount = 0;
                foreach (GraphEdge edge in editor.edges)
                {
                    graph.AddEdge(new LayoutEdge(edge));
                    edgeCount++;
                }

                // GraphSharp crashes if less than 2 nodes or less than 1 edge
                if (nodeCount < 2 || edgeCount < 1)
                    return false;

                // A lot of code for basically a single operation...
                LayoutContext<GraphNode, LayoutEdge, BidirectionalGraph<GraphNode, LayoutEdge>> context =
                    new LayoutContext<GraphNode, LayoutEdge, BidirectionalGraph<GraphNode, LayoutEdge>>
                    (graph, positions, sizes, LayoutMode.Simple);
                ILayoutAlgorithm<GraphNode, LayoutEdge, BidirectionalGraph<GraphNode, LayoutEdge>> algorithm =
                    _factory.CreateAlgorithm(ALGORITHM_NAME, context, _parameters);
                algorithm.Compute();

                double minx = 0;
                double miny = 0;
                foreach (KeyValuePair<GraphNode, Point> kvp in algorithm.VertexPositions)
                {
                    Point p = reverse(kvp.Value);
                    minx = Math.Min(minx, p.X - (kvp.Key.RenderSize.Width / 2));
                    miny = Math.Min(miny, p.Y - (kvp.Key.RenderSize.Height / 2));
                }
                double xOfs = -minx + MIN_CANVAS_OFFSET;
                double yOfs = -miny + MIN_CANVAS_OFFSET;
                if(xOfs < 0) xOfs = 0;
                if(yOfs < 0) yOfs = 0;

                foreach (KeyValuePair<GraphNode, Point> kvp in algorithm.VertexPositions)
                {
                    Point p = reverse(kvp.Value);
                    double x = (p.X - (kvp.Key.RenderSize.Width / 2)) + xOfs;
                    double y = (p.Y - (kvp.Key.RenderSize.Height / 2)) + yOfs;
                    editor.snapIfNeeded(ref x, ref y);
                    kvp.Key.left = x;
                    kvp.Key.top = y;
                }
            }
            catch (Exception e)
            {
                _log.error(e, "Error during graph layout");
                return false;
            }
            finally
            {
                editor.cursor = Cursors.Arrow;
                editor.isEnabled = true;
            }
            return true;
        }

        private static Point reverse(Point p) { return new Point(p.Y, p.X); }
        private static Size reverse(Size p) { return new Size(p.Height, p.Width); }

        private sealed class LayoutEdge : IEdge<GraphNode>
        {
            private readonly GraphEdge _edge;
            public LayoutEdge(GraphEdge edge) { _edge = edge; }
            public GraphNode Source { get { return _edge.output.node; } }
            public GraphNode Target { get { return _edge.input.node; } }
        }
    }
}